package xs.szw.service.expression;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xs.szw.common.exception.BusinessException;
import xs.szw.common.result.Result;
import xs.szw.common.result.ResultCode;

/**
 * @program: xs_oa
 * @description:
 * @author: Songzw
 * @create: 2025-02-07 09:38
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 全局异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleGeneralException(Exception ex) throws Exception {
        // 在全局异常处理器中，认证异常（AuthenticationException）和授权异常（AccessDeniedException）不应被捕获，否则这些异常将无法交给 Spring Security 的异常处理机制进行处理。
        //  因此，当捕获到这类异常时，应该将其重新抛出，交给 Spring Security 来处理其特定的逻辑
        if (ex instanceof AccessDeniedException || ex instanceof AuthenticationException) {
            throw  ex;
        }
        log.error("全局异常:{}",ex.getMessage());
        return Result.fail(ResultCode.RC500.getCode(),ex.getMessage());
    }

    /**
     * @VALId 注解字段校验异常处理
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        FieldError error = result.getFieldError();
        return Result.fail(ResultCode.FILED_VALIDATION_CODE_ERROR.getCode(),error != null ? error.getDefaultMessage() : "请求参数错误");
    }

//    /**
//     * 自定义业务异常
//     * @param businessException
//     * @return
//     */
//    @ExceptionHandler(BusinessException.class)
//    public Result<Object> handleBusinessException(BusinessException businessException) {
//        log.error("BusinessException:{}",businessException.getMessage());
//        return Result.fail(ResultCode.RC500.getCode(),businessException.getMessage());
//    }


}
